# -*- coding: utf-8 -*-
# @Time : 2025/1/25 13:57
# @Author : debbyszhang
# @File : cross_gateway_list_page.py
# @desc :
import time
from typing import List, Dict

from playwright.sync_api import Page

from config.settings import PROJECT_ROOT
from libs.base_page import BasePage

import re


class CrossGatewayListPage(BasePage):
    """
    跨链网关列表页面
    """

    def __init__(self, page: Page):
        super().__init__(page)
        # self.url = "http://192.168.0.173:8088"
        # self.url = BASE_URL + "/login"
        self.chain_rid = "请输入链资源ID"
        self.chain_id = "请输入Chain ID"
        self.org_id = "请输入组织ID"
        self.cross_contract_name = "请输入跨链合约名称"
        self.sign_crt = re.compile(r"交易签名私钥点击上传/拖拽到此区域支持\.crt格式文件$")
        self.sign_key = re.compile(r"交易签名私钥点击上传/拖拽到此区域支持\.key格式文件$")
        self.sign_key_file = PROJECT_ROOT + '/libs/certs/chainmaker/crypto-config/wx-org1.chainmaker.org/user/client1/client1.sign.key'
        self.sign_crt_file = PROJECT_ROOT + '/libs/certs/chainmaker/crypto-config/wx-org1.chainmaker.org/user/client1/client1.sign.crt'
        self.tls_key_file = PROJECT_ROOT + '/libs/certs/chainmaker/crypto-config/wx-org1.chainmaker.org/user/client1/client1.tls.key'
        self.tls_crt_file = PROJECT_ROOT + '/libs/certs/chainmaker/crypto-config/wx-org1.chainmaker.org/user/client1/client1.tls.crt'
        self.ca_crt_file = PROJECT_ROOT + '/libs/certs/chainmaker/crypto-config/wx-org1.chainmaker.org/ca/ca.crt'
        self.tls_crt = r"点击上传/拖拽到此区域支持\.crt格式文件$"
        self.tls_key = r"点击上传/拖拽到此区域支持\.key格式文件$"
        self.ip = "RPC地址可填写IP:端口或域名"
        self.hostname = "请输入TLS hostname"
        self.ca_crt = "点击上传"
        self.make_sure = "确定"
        # self.page.screenshot(path="./ccccc1111.png")
        self.page.get_by_role("link", name="跨链网关").click()
        # self.page.screenshot(path="./ccccc.png")

    def logout(self):
        self.page.locator(".tea-dropdown").nth(1).hover()
        self.page.get_by_text('退出登录').click()

    def flip_over(self):
        wait_time = 2
        # 最后一页
        self.page.get_by_role("main").locator("a").nth(3).click()
        time.sleep(wait_time)
        # 第一页
        self.page.get_by_role("main").locator("a").first.click()
        time.sleep(wait_time)
        # 后一页
        self.page.get_by_role("main").locator("a").nth(2).click()
        time.sleep(wait_time)
        # 前一页
        self.page.get_by_role("main").locator("a").nth(1).click()
        time.sleep(wait_time)

    def search_gateway(self, content):
        """
        搜索功能
        :return:
        """
        self.click_fill("请输入网关名称", content)
        self.page.get_by_placeholder("请输入网关名称").press("Enter")
        self.click('搜索')
        time.sleep(1)

    def new_gateway(self, gateway_name):
        self.click("创建网关")
        self.click_fill("请输入跨链网关名称", gateway_name)
        self.click_fill("请输入IP地址:端口或域名", "192.1.12.12:12")
        self.click_fill("请输入监听端口信息", "1112")
        self.click("确定")
        time.sleep(1)

    def new_event(self, topic_id, target_gateway_id, target_chainrid, target_contract, try_method):
        self.page.locator("button:nth-child(5)").click()
        self.click_fill("请输入业务合约topic ID", topic_id)
        self.click_fill("请输入目标网关ID", target_gateway_id)
        self.click_fill("请输入目标链资源ID", target_chainrid)
        self.click_fill("请输入目标链合约名", target_contract)
        self.click_fill("请输入方法名", try_method)
        self.click('确定')

    def apply(self, row_number):
        self.page.get_by_role("button", name="授权申请").nth(row_number).click()
        self.click_fill("请输入中继网关ID", "MAIN_GATEWAY_ID00")
        self.click_fill("请输入中继网关名称", "relayer")
        self.click_fill("请输入中继网关控制台地址", "http://102.14.12.12:8088")
        self.click_fill("请输入中继网关控制台获取的token信息", "12")
        self.click_fill("请输入跨链网关所在控制台地址", "http://102.14.12.12:8088")
        self.click_fill("请输入接入申请说明", "reasonaaa")
        time.sleep(1)
        # 获取并点击“确定”按钮
        confirm_button = self.page.locator(".tea-dialog__footer button", has_text="确定")
        confirm_button.click()
        time.sleep(1)
        t = self.page.locator("#tea-message-root div").inner_text()
        print(t)
        return t

    def add_subchain(self, chain_rid, chain_id, org_id, cross_contract_name, ip, hostname):
        """
        添加子链
        :param chain_rid:
        :param chain_id:
        :param org_id:
        :param cross_contract_name:
        :param ip:
        :param hostname:
        :return:
        """
        # self.page.get_by_role("link", name="跨链网关").click()
        self.page.locator("td:nth-child(7) > div > button:nth-child(2)").click()
        # page.get_by_placeholder("请输入链资源ID").click()
        # page.get_by_placeholder("请输入链资源ID").fill("chain001")
        # page.get_by_placeholder("请输入Chain ID").click()
        # page.get_by_placeholder("请输入Chain ID").fill("chain1")

        # self.page.wait_for_selector("input[type='file']")
        self.click_fill(self.chain_rid, chain_rid)
        self.click_fill(self.chain_id, chain_id)
        self.select("公钥模式", "证书模式")
        # self.select("国密SM3", "非国密SHA256")
        self.page.get_by_placeholder("请输入组织ID").click()
        self.page.get_by_placeholder("请输入组织ID").fill("wx-org1.chainmaker.org")
        self.page.get_by_placeholder("请输入跨链合约名称").click()
        self.page.get_by_placeholder("请输入跨链合约名称").fill("batchContract")

        with self.page.expect_file_chooser() as fc_info:
            self.page.locator("div").filter(has_text=re.compile(r"^交易签名私钥点击上传/拖拽到此区域支持\.key格式文件$")).locator("button").click()
        file_chooser = fc_info.value
        file_chooser.set_files(self.sign_key_file)

        with self.page.expect_file_chooser() as fc_info:
            self.page.locator("div").filter(has_text=re.compile(r"^交易签名证书点击上传/拖拽到此区域支持\.crt格式文件$")).locator("button").click()
        file_chooser = fc_info.value
        file_chooser.set_files(self.sign_crt_file)
        self.screenshot(path="./screenshots/add_sub_chainmaker1.png")

        with self.page.expect_file_chooser() as fc_info:
            self.page.locator("div").filter(has_text=re.compile(r"^点击上传/拖拽到此区域支持\.crt格式文件$")).locator("button").click()
        file_chooser = fc_info.value
        file_chooser.set_files(self.tls_crt_file)

        with self.page.expect_file_chooser() as fc_info:
            self.page.locator("div").filter(has_text=re.compile(r"^点击上传/拖拽到此区域支持\.key格式文件$")).locator("button").click()
        file_chooser = fc_info.value
        file_chooser.set_files(self.tls_key_file)
        self.screenshot(path="./screenshots/add_sub_chainmaker2.png")

        self.page.get_by_placeholder("RPC地址可填写IP:端口或域名").click()
        self.page.get_by_placeholder("RPC地址可填写IP:端口或域名").fill("192.168.1.242:12301")
        self.page.locator("label").filter(has_text=re.compile(r"^是$")).locator("i").click()
        self.page.get_by_placeholder("请输入TLS hostname").click()
        self.page.get_by_placeholder("请输入TLS hostname").fill("chainmaker.org")
        self.screenshot(path="./screenshots/add_sub_chainmaker3.png")

        with self.page.expect_file_chooser() as fc_info:
            self.page.locator("div").filter(has_text=re.compile(r"^TLS通讯证书点击上传/拖拽到此区域支持\.crt格式文件$")).locator("button").click()
        file_chooser = fc_info.value
        file_chooser.set_files(self.ca_crt_file)
        self.screenshot(path="./screenshots/add_sub_chainmaker4.png")

        self.page.get_by_role("button", name="确定").click()
        t = self.page.locator("#tea-message-root div").inner_text()
        print(t)  # '新增成功'
        return t

    def get_gateway_list_data(self, title, num=0):
        headers = self.page.locator("table thead tr th")
        headers_text = [header.text_content() for header in headers.all()]
        print("表头:", headers_text)

        rows = self.page.locator("table tbody tr")
        if rows.count() == 0:
            print("列表中没有数据")

        # 获取第一行数据
        first_row = rows.nth(num)
        cells = first_row.locator("td")
        cells_text = [cell.text_content() for cell in cells.all()]
        print(f"第{num + 1}行数据:", cells_text)

        # 提取网关名称
        value_index = headers_text.index(title)
        value = cells_text[value_index]
        print("数据:", value)

        return value

    def gateway_list(self) -> List:
        """
        跨链网关列表（点击后的展示的数据）
        :return:
        """
        self.page.get_by_role("link", name="跨链网关").click()

        data_list = self.get_gateway_list()
        return data_list

        # # 获取表头
        # headers = self.page.locator("table th").all()
        # headers = [header.text_content() for header in headers]
        #
        # # 获取所有表格行
        # rows = self.page.locator("table tbody tr").all()
        #
        # data_list = []
        # for row in rows:
        #     # 获取当前行的所有单元格
        #     cells = row.locator("td").all()
        #     cells = [cell.text_content() for cell in cells]
        #
        #     # 创建字典并添加到列表中
        #     data_dict = dict(zip(headers, cells))
        #     data_list.append(data_dict)
        #
        # return data_list

    def get_gateway_list(self) -> List:
        """
        获取跨链网关列表数据（用于搜索后获取返回结果）
        :return:
        """
        # 获取表头
        headers = self.page.locator("table th").all()
        headers = [header.text_content() for header in headers]

        # 获取所有表格行
        rows = self.page.locator("table tbody tr").all()

        data_list = []
        for row in rows:
            # 获取当前行的所有单元格
            cells = row.locator("td").all()
            cells = [cell.text_content() for cell in cells]

            # 创建字典并添加到列表中
            data_dict = dict(zip(headers, cells))
            data_list.append(data_dict)

        return data_list

    def gateway_list_data(self, row_number) -> Dict:
        """
        获取指定行的数据
        :param row_number:
        :return:
        """
        # 等待页面加载完成
        # self.page.wait_for_selector("table tbody tr", state="visible")
        time.sleep(2)
        rows = self.page.locator("table tbody tr").all()
        # 定位到表格行
        target_row = rows[row_number]
        # 获取行中的所有单元格
        cells = target_row.locator('td').all()
        # 获取表头
        headers = self.page.locator("table.tea-table__box th").all()
        headers_text = [header.text_content() for header in headers]
        # 提取单元格中的文本内容
        row_data = {}
        for header, cell in zip(headers_text, cells):
            text = cell.text_content().strip()
            row_data[header] = text
        print(row_data)
        return row_data

    def gateway_info(self, name):
        """
        跨链网关信息
        :return:
        """
        self.page.get_by_role("button", name=name).click()
        return self.page
